"""
Copyright 2009 Texas A&M University
 
Licensed under the Apache License, Version 2.0 (the "License"); you may not use 
this file except in compliance with the License. You may obtain a copy of the 
License at

http://www.apache.org/licenses/LICENSE-2.0
  
Unless required by applicable law or agreed to in writing, software distributed 
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
CONDITIONS OF ANY KIND, either express or implied. See the License for the 
specific language governing permissions and limitations under the License. 
"""

from logging import getLogger

from meercat.interfaces import IResource, IInstance, IMetadata, IPickleable
from meercat.base.resource import Resource
from meercat.base.instance import Instance
from meercat.base.metadata import Metadata



log = getLogger('meercat.base.pickleable')

def pickleResource(resource):
    log.debug('pickleResource(%s)' % (str(resource)))
    resource = IResource(resource)
    return Resource(identifier=resource.getIdentifier(),
                    instances=resource)

def pickleInstance(instance):
    log.debug('pickleInstance(%s)' % (str(instance)))
    instance = IInstance(instance)
    
    resource = instance.getResource()
    
    """ Don't attempt to pickle parents (stops loops) """
    if not resource or not IPickleable.providedBy(resource):
        log.debug('pickleInstance(%s) not setting resource' % (str(instance),))
        resource = None
    
    return Instance(source=instance.getSource(),
                    identifier=instance.getIdentifier(),
                    active=instance.isActive(),
                    metadata=instance.getMetadata(),
                    modified=instance.getLastModified(),
                    resource=resource)

def pickleMetadata(metadata):
    log.debug('pickleMetadata(%s)' % (str(metadata)))
    metadata = IMetadata(metadata)
    
    instance = metadata.getInstance()
    
    """ Don't attempt to pickle parents (stops loops) """
    if not instance or not IPickleable.providedBy(instance):
        log.debug('pickleMetadata(%s) not setting instance' % (str(metadata)))
        instance = None
    
    return Metadata(format=metadata.getFormat(),
                    source=metadata.getSource(),
                    value=metadata.getValue(),
                    instance=instance)